/*
 * AnimalPosition.hpp
 *
 *  Created on: 2013-1-17
 *      Author: heqiu
 */

#ifndef ANIMALPOSITION_HPP_
#define ANIMALPOSITION_HPP_

#include "AnimalUnit.hpp"
#include "MyLock.hpp"
using namespace std;

class AnimalPosition {
public:
	map<uint32_t, uint32_t> m_mapAnimal;
	map<uint32_t, set<uint32_t> > m_mapPos;
	AnimalPosition() {
		m_uiLong = 0;
	}
	~AnimalPosition() {
	}
	void init(uint32_t uiLong) {
		m_uiLong = uiLong;
	}
	void getAnimal(uint32_t uiX, uint32_t uiY, vector<uint32_t> & vctAnimal) {
		uint32_t uiPos = uiX * (m_uiLong + 1) + uiY;
		m_lock.lock();
		map<uint32_t, set<uint32_t> >::iterator it = m_mapPos.find(uiPos);
		if (it != m_mapPos.end()) {
			set<uint32_t> & tmpSet = it->second;
			set<uint32_t>::iterator itSet;
			for (itSet = tmpSet.begin(); itSet != tmpSet.end(); itSet++) {
				vctAnimal.push_back(*itSet);
			}
		}
		m_lock.unlock();
	}
	void delAnimal(uint32_t uiId) {
		m_lock.lock();
		map<uint32_t, uint32_t>::iterator it = m_mapAnimal.find(uiId);
		if (it != m_mapAnimal.end()) {
			m_mapPos[it->second].erase(it->first);
			m_mapAnimal.erase(it);
		}
		m_lock.unlock();
	}
	void addAnimal(uint32_t uiId, uint32_t uiX, uint32_t uiY) {
		uint32_t uiPos = uiX * (m_uiLong + 1) + uiY;
		m_lock.lock();
		map<uint32_t, uint32_t>::iterator it = m_mapAnimal.find(uiId);
		if (it == m_mapAnimal.end()) {
			m_mapAnimal[uiId] = uiPos;
			m_mapPos[uiPos].insert(uiId);
		} else {
			if (it->second != uiPos) {
				m_mapPos[it->second].erase(uiId);
				it->second = uiPos;
				m_mapPos[uiPos].insert(uiId);
			}
		}
		m_lock.unlock();
	}
private:
	uint32_t m_uiLong;
	MyLock m_lock;
};

#endif /* ANIMALPOSITION_HPP_ */
